package com.baimsg

import com.github.unidbg.AndroidEmulator
import com.github.unidbg.Module
import com.github.unidbg.arm.backend.Unicorn2Factory
import com.github.unidbg.linux.android.AndroidEmulatorBuilder
import com.github.unidbg.linux.android.AndroidResolver
import com.github.unidbg.linux.android.dvm.DvmClass
import com.github.unidbg.linux.android.dvm.DvmObject
import com.github.unidbg.linux.android.dvm.VM
import java.io.File

class Etalk {
    private var emulator: AndroidEmulator

    private var jniManagerUtil: DvmClass
    private var vm: VM

    private var module: Module

    init {
        val currentDirectory = System.getProperty("user.dir")
        val BASE_PATH = File(currentDirectory, "data")

        emulator = AndroidEmulatorBuilder.for64Bit().setProcessName("com.baitai.etalk")
            .addBackendFactory(Unicorn2Factory(true)).build()
        val memory = emulator.memory
        memory.setLibraryResolver(AndroidResolver(23))
        vm = emulator.createDalvikVM()
        vm.setVerbose(true)
        val dm = vm.loadLibrary(File(BASE_PATH, "l578c82f6.so"), false)
        emulator.memory.loadedModules.forEach(::println)
        module = dm.module
        vm.printMemoryInfo()

        jniManagerUtil = vm.resolveClass("")
    }

    fun destroy() {
        emulator.close()
    }

    fun getEncryptionKey() {
        val methodStringFromJNI = "l578c82f6_11(Ljava/lang/String)Ljava/lang/String;"
        //        byte[] param = new byte[]{-105, -68, 25, -14, 100, -120};;
        jniManagerUtil.fieldMap.forEach(::println)
        jniManagerUtil.methodMap.forEach(::println)
        val strRc = jniManagerUtil.newObject(null).callJniMethodObject<DvmObject<*>>(
            emulator, methodStringFromJNI, "6A12362236390B39353C3A0C342C420E314539493B494D"
        )
        if (strRc == null) println("_getEncryptionKey返回值：null")
        else println("_getEncryptionKey返回值：" + strRc.value)
    }
}

fun main() {
    val talk = Etalk()
    talk.getEncryptionKey()
    talk.destroy()
}